/**
 * Created by Wing on 2017/5/22.
 */

// 根据值来删除数组中的元素
var removeByValue = function (arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}
// 判断元素是否在数组中
var inArray = function (arr, item) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == item) {
            return true;
        }
    }
    return false;
};
// 在json里面的索引
var arr = [0, 1];
var indexOfConditionMap = {
    "deckName": 0,
    "noteCreateTime": 1,
    "noteEditTime": 2,
    "noteTypeName": 3,
    "cardStyleName": 4,
    "cardNextStudyTime": 1,
    "cardHardFactory": 6,
    "cardStudyCount": 7,
    "cardWrongCount": 8
}


var json;
var firstIndexOfConditoion = 0;
var addCondition = function (conditionName, conditionValue, conditionPattern, conditionFrom, conditionTo) {
    if (conditionName == undefined || conditionPattern == undefined || (conditionValue == undefined && conditionFrom == undefined)) {
        // 要么三个都为undefine,要么三个都有值
        conditionName = undefined;
        conditionPattern = undefined;
        conditionValue = undefined;
    }
    // 当前添加的是第几个条件
    var indexOfLi = firstIndexOfConditoion++;
    var indexOfCondition = arr[0];
    if (conditionName != undefined) {
        indexOfCondition = indexOfConditionMap[conditionName];
    } else {

    }

    console.log("index:" + indexOfCondition);
    // 删除当前
    //arr.splice(0, 1);
    removeByValue(arr, indexOfCondition);
    console.log("新增:" + arr);
    $.getJSON(
        'test.json',
        function (_json) {
            json = _json;
            var condition = json['sel'][indexOfCondition];
            var patternIndex = -1;
            if ((conditionValue != undefined || conditionFrom != undefined) && conditionPattern != undefined) {
                $.each(condition.pattern, function (i, p) {
                    if (p.value == conditionPattern) {
                        patternIndex = i;
                    }
                })
            }
            if (patternIndex == -1) {
                patternIndex = 0;
            }
            console.log(condition.text);
            conditionName = condition.text;
            // 头
            var h = '<div id="condition' + indexOfLi + '" class="input-group">';
            // 选择
            h += '<div id="conditionName' + indexOfLi + '" class="sel1 input-group-btn" data-id="0" name="sel1">';
            h += '<button type="button" id="conditionNameBtn' + indexOfLi + '" name="' + indexOfCondition + '" class="btn btn-default dropdown-toggle" data-toggle="dropdown" ' +
                'aria-haspopup="true" aria-expanded="false" value="' + condition.key + '">' + condition.text + '<span' +
                ' class="caret"' +
                ' style="margin-left:0.5em"></span></button>';
            h += '<ul class="dropdown-menu" id="conditionNameUl' + indexOfLi + '"> ';
            // 以往的条件名称下拉菜单
            for (var i = 0; i < indexOfLi; i++) {
                $("#conditionNameUl" + i).html('');
                var c = "";
                $(json['sel']).each(function (j, condition) {
                    if (inArray(arr, j)) {
                        // 还在数组中,表明没有选中
                        c += '<li>' +
                            '<a disable="able" href="javascript:" name="' + i + '" value="' + condition.value + '" key="'+condition.key+'" > ' +
                            condition.text +
                            '</a></li>';
                    } else {
                        c += '<li>' +
                            '<a disable="disable" href="javascript:" name="' + i + '" value="' + condition.value + '" key="'+condition.key+'"> ' +
                            condition.text +
                            '</a></li>';
                    }
                });

                $("#conditionNameUl" + i).html(c);
                $("#conditionName" + i + " a[disable=able]").click(changeConditionName);

            }
            // 当前条件名称下拉菜单
            $(json['sel']).each(function (i, condition) {
                if (inArray(arr, i)) {
                    h += '<li>' +
                        '<a disable="able" href="javascript:" name="' + indexOfLi + '" value="' + condition.value + '"key="'+condition.key+'" > ' +
                        condition.text +
                        '</a></li>';
                } else {
                    h += '<li>' +
                        '<a disable="disable" href="javascript:" name="' + indexOfLi + '" value="' + condition.value + '" key="'+condition.key+'"> ' +
                        condition.text +
                        '</a></li>';
                }

            });
            h += '</ul>';
            h += '</div>';
            // 条件
            h += '<div id="conditionPattern' + indexOfLi + '" class="sel1 input-group-btn patterns" data-id="0" name="sel1">';
            h += '<button type="button" id="conditionPatternBtn' + indexOfLi + '" class="btn btn-default' +
                ' dropdown-toggle" data-toggle="dropdown" ' +
                'aria-haspopup="true" aria-expanded="false" value="' + condition.pattern[patternIndex].value + '">' + $(condition.pattern)[patternIndex].text + ' <span' +
                ' class="caret"></span></button>';
            h += '<ul class="dropdown-menu">';
            $(condition.pattern).each(function (i, p) {
                h += "<li>" +
                    "<a href=\"javascript:changeDropDownBtnValue('" + p.text + "','conditionPatternBtn" + indexOfLi + "','" + p.value + "')\"" +
                    " name='" + indexOfLi + "' value='" + p.value + "' >" +
                    p.text +
                    "</a></li>";
            });
            h += '</ul>';
            h += '</div>';
            if (conditionName.indexOf("Time") != -1) {
                // 如果有时间
                if (conditionValue != undefined) {
                    conditionValue = new Date(conditionValue).toString();
                } else {
                    conditionFrom = new Date(conditionFrom).toString();
                    conditionTo = new Date(conditionTo).toString();
                }
            }
            // 尾
            if (conditionValue != undefined) {
                h += '<input id="conditionPatternInput' + indexOfLi + '" type="text" class="form-control"' +
                    ' value="' + conditionValue + '" style="width:170px"' +
                    ' aria-label="...">';

            } else {
                if (conditionPattern == "inrange") {
                    h += '<input id="conditionPatternInput' + indexOfLi + '" type="text" class="form-control"' +
                        ' value="' + conditionFrom + '" style="width:170px"' +
                        ' aria-label="...">';

                    h += '<input id="conditionPatternInputTo' + indexOfLi + '" type="text" class="form-control"' +
                        ' value="' + conditionTo + '" style="width:170px"' +
                        'aria-label="...">';
                } else {
                    h += '<input id="conditionPatternInput' + indexOfLi + '" type="text" class="form-control"' +
                        '  style="width:170px" aria-label="...">';
                }
            }

            h += '<a id="reduceBtn' + indexOfLi + '" href="javascript:" class="reduceBtn">-</a>' +
                '<a id="addBtn' + indexOfLi + '" href="javascript:" class="addBtn">+</a>' +
                '</div>';
            $("#formDiv").append(h);
            $("#addBtn" + indexOfLi).click(addCondition);
            $("#reduceBtn" + indexOfLi).click(reduceCondition);
            $("#conditionName" + indexOfLi + " a[disable=able]").click(changeConditionName);
            $("#addBtn" + indexOfLi).addClass("addBtn");
            $("#conditionName" + indexOfCondition).trigger("create");
            $("div[id^=conditionPattern] .dropdown-menu a").click(changeConditionPattern);
        }
    );
};
// 在条件模式下的a标签被点击的时候调用
var changeConditionPattern = function (event) {
    var a = $(event).attr('delegateTarget');
    var pattern = $(a).attr("value");
    var indexOfLi = $(a).attr("name");
    if (pattern == "inrange") {
        // 先拿到已有的input
        var input = $("#conditionPatternInput" + indexOfLi);
        if ($("#conditionPatternInputTo" + indexOfLi).attr("id") != undefined) {
            // 如果已经被定义，则跳过
            return;
        }
        ;
        var inputTo = '<input id="conditionPatternInputTo' + indexOfLi + '" type="text" class="form-control"' +
            '  style="width:170px" aria-label="...">';
        input.after(inputTo);
    } else {
        var inputTo = $("#conditionPatternInputTo" + indexOfLi);
        inputTo.remove();
    }
    // $("#conditionPatternInput" + indexOfLi).val("");
}
var addConditionsFromDefaultConditions = function () {
    for (var conditionName in defaultConditions) {
        if (conditionName in indexOfConditionMap) {
            var condition = defaultConditions[conditionName];
            if(condition.value == undefined){
                condition.value = condition.relativeValue;
            }
            addCondition(conditionName, condition.value, condition.pattern, condition.from, condition.to);
        }
    }
}
var currentChangeSelectId;

var changeConditionName = function (event) {
    var a = $(event).attr('delegateTarget');
    var indexOfLi = $(a).attr('name');
    var indexOfCondition = $(a).attr('value');
    changeDropDownBtnValue($(a).text(),"conditionNameBtn"+indexOfLi,$(a).attr("key"));
    console.log(indexOfLi);
    $.getJSON(
        'test.json',
        function (json) {
            var condition = json['sel'][indexOfCondition];
            $("#conditionNameBtn" + indexOfLi).html(condition.text + '<span class="caret" style="margin-left:0.5em"></span>');
            // 之前选中的条件
            var beforeIndex = $("#conditionNameBtn" + indexOfLi).attr("name");
            console.log("beforeIndex:" + beforeIndex);
            // 名称按钮刷新
            arr.splice(0, 0, beforeIndex);
            $("#conditionNameBtn" + indexOfLi).attr({
                "name": indexOfCondition,
                "value": condition.key
            });

            removeByValue(arr, indexOfCondition);
            console.log("更改:" + arr);
            for (var i = 0; i <= indexOfLi; i++) {
                $("#conditionNameUl" + i).html('');
                var c = "";
                $(json['sel']).each(function (j, condition) {
                    if (inArray(arr, j)) {
                        // 还在数组中,表明没有选中
                        c += '<li>' +
                            '<a disable="able" href="javascript:" name="' + i + '" value="' + condition.value + '"key="'+condition.key+'" > ' +
                            condition.text +
                            '</a></li>';
                    } else {
                        c += '<li>' +
                            '<a disable="disable" href="javascript:" name="' + i + '" value="' + condition.value + '"key="'+condition.key+'" > ' +
                            condition.text +
                            '</a></li>';
                    }
                });

                $("#conditionNameUl" + i).html(c);
                $("#conditionName" + i + " a[disable=able]").click(changeConditionName);
            }
            // 条件按钮刷新
            $("#conditionPattern" + indexOfLi).html("");
            var h = "";
            h += '<button type="button" id="conditionPatternBtn' + indexOfLi + '" class="btn btn-default' +
                ' dropdown-toggle" data-toggle="dropdown" ' +
                'aria-haspopup="true" aria-expanded="false" value="' + condition.pattern[0].value + '">' + $(condition.pattern)[0].text + ' <span' +
                ' class="caret"></span></button>';
            h += '<ul class="dropdown-menu">';
            $(condition.pattern).each(function (i, p) {
                h += "<li>" +
                    "<a href=\"javascript:changeDropDownBtnValue('" + p.text + "','conditionPatternBtn" + indexOfLi + "','" + p.value + "')\"" +
                    " name='" + indexOfLi + "' value='" + p.value + "' >" +
                    p.text +
                    "</a></li>";
            });
            h += '</ul>';
            $("#conditionPattern" + indexOfLi).append(h);
            // valueInput清空
            $("#conditionPatternInput" + indexOfLi).val("");
            $("#conditionPatternInputTo" + indexOfLi).remove();
            $("div[id^=conditionPattern] .dropdown-menu a").click(changeConditionPattern);
        }
    );
    console.log($("#conditionNameBtn" + indexOfLi));

}

var reduceCondition = function (event) {
    var btn = $(event).attr('delegateTarget');
    var btnId = $(btn).attr('id');
    var divId = btnId.replace("reduceBtn", "condition");
    // 第几行
    var indexOfLi = btnId.replace("reduceBtn", "");
    // 第几个条件
    var indexOfCondition = $("#conditionNameBtn" + indexOfLi).attr("name");
    var length = json['sel'].length;
    if (arr.length < length - 1) {
        // 剩余个数小于8,即已选择条件大于1个才能删除(总共有9个条件)
        var conditionDiv = $("#" + divId);
        $(conditionDiv).remove();

        // 之前选中的条件
        //var beforeIndex = $("#conditionNameBtn" + indexOfCondition).attr("name");
        console.log("beforeDelete:" + indexOfCondition);
        // 名称按钮刷新
        arr.splice(0, 0, indexOfCondition);

        for (var i = 0; i < firstIndexOfConditoion; i++) {
            // 给所有的条件div中的名称下拉菜单重新赋值
            $("#conditionNameUl" + i).html('');
            var c = "";
            $(json['sel']).each(function (j, condition) {
                if (inArray(arr, j)) {
                    // 还在数组中,表明没有选中
                    c += '<li>' +
                        '<a disable="able" href="javascript:" name="' + i + '" value="' + condition.value + '" > ' +
                        condition.text +
                        '</a></li>';
                } else {
                    c += '<li>' +
                        '<a disable="disable" href="javascript:" name="' + i + '" value="' + condition.value + '" > ' +
                        condition.text +
                        '</a></li>';
                }
            });

            $("#conditionNameUl" + i).html(c);
            $("#conditionName" + i + " a[disable=able]").click(changeConditionName);
        }
    }
};
$(function () {
    if ($("h2").html() == "编辑学习列表") {
        $("#submitBtnId").click(editorStudyList);
    } else {
        $("#submitBtnId").click(submitStudyList);
    }
});
// return map
var getConditionMap = function () {
    var map = {
        "studyListName": $("input[name=studyListName]").val(),
        "screenConditions_json": ""
    };
    if($("input[name=studyListName]").val().trim() == ""){
        showTip("请输入学习列表名称!",undefined,false);
        throw "请输入名称"
    }
    if (studyListId != undefined) {
        map["studyListId"] = studyListId;
    }
    if (userId != undefined) {
        map["userId"] = userId;
    }
    if (studySchemeId != undefined) {
        map["studySchemeId"] = studySchemeId;
    }
    var screenMap = {};
    for (var i = 0; i < firstIndexOfConditoion; i++) {
        if ($("#condition" + i).attr("id") != undefined) {
            // 找到的是一个div
            console.log($("#condition" + i));
            var conditonKey = $("#conditionNameBtn" + i).val();
            var conditionPattern = $("#conditionPatternBtn" + i).val();

            var conditionPatternValue = $("#conditionPatternInput" + i).val();
            if(conditionPatternValue.trim() == ""){
                // 没有输入则跳过
                continue;
            }
            var conditionPatternValueTo;
            var conditionMap;
            if(parseInt(conditionPatternValue).toString() == conditionPatternValue.trim()){
                // 只有数字
                conditionMap = {"pattern": conditionPattern, "relativeValue": parseInt(conditionPatternValue)};
            }else{
                conditionMap = {"pattern": conditionPattern, "value": conditionPatternValue};
            }
            if (conditonKey.indexOf("Time") != -1) {// 如果当前查询的是时间
                // 如果有中文
                var reg = /^[\u4E00-\u9FA5]+$/;
                if(reg.test(conditionPatternValue)){
                    // 有中文
                    showTip("时间的筛选条件不能有中文!",undefined,false);
                    throw "有中文"
                }
            }
            // if (conditionPattern == "inrange") {
            //     conditionPatternValueTo = $("#conditionPatternInputTo" + i).val();
            //     var conditionMap = {
            //         "pattern": conditionPattern,
            //         "from": conditionPatternValue,
            //         "to": conditionPatternValueTo
            //     };
            // }
            screenMap["userId"] = userId;
            screenMap[conditonKey] = conditionMap;
        }
    }

    map["screenConditions_json"] = JSON.stringify(screenMap);
    return map;
}
var submitStudyList = function () {
    try {
        var map = getConditionMap();
        $.ajax({
            'url': '/memorypalace/study/insertsl.action',
            'type': 'POST',
            'data': map,
            'success': function () {
                console.log("成功");
                window.location.href = "/memorypalace/study/getsl.action";
                // history.go(1);
            }
        });
        console.log("新增学习列表：");
        console.log(JSON.stringify(map));
    }catch (err){
    }

}

var editorStudyList = function () {
    try {
        var map = getConditionMap();
        $.ajax({
            'url': '/memorypalace/study/updatesl.action',
            'type': 'get',
            'data': map,
            'success': function () {
                console.log("成功");
                window.location.href = "/memorypalace/study/getsl.action";
                // history.go(1);
            }
        });
        console.log("编辑学习列表：");
        console.log(JSON.stringify(map));
    }catch (err){
    }
}


